package com.knife.bbs.business;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;

import com.knife.dbo.EasyJDB;

import com.knife.web.ActionContext;
import com.knife.web.tools.DbPageList;
import com.knife.web.tools.IPageList;
import com.knife.bbs.domain.BBSScore;
import com.knife.bbs.domain.Friend;
import com.knife.bbs.domain.Score;
import com.knife.bbs.object.UserInfo;

public class BBSUserService extends DAOSupportService {
	private static BBSUserService singleton = new BBSUserService();

	public static BBSUserService getInstance() {
		return singleton;
	}

	public ActiveUser login(String userName, String password, String cktime,
			String ip) {
		ActiveUser user = null;
		com.knife.bbs.domain.UserInfo u = (com.knife.bbs.domain.UserInfo) this.dao.getBy(com.knife.bbs.domain.UserInfo.class, "username", userName);
		if (u != null && password.equals(u.getPassword().trim())) {
			user = new ActiveUser();
			// user.setUserName(u.getUserName().trim());
			user.setUsername(userName);
			user.setIp(ip);
			user.setCurposition("当前位置");
			user.setPassword(u.getPassword().trim());
			user.setLogintime(new Date());
			//u.setUsername(userName);
			u.setLastloginip(ip);
			u.setLogintimes(new Integer(u.getLogintimes() == null ? 1 : u
					.getLogintimes().intValue() + 1));
			
			this.dao.update(u);
			//activeUserService.join(user);
		}
		String value = userName + "_" + password;
		Cookie cookie = new Cookie("com.knife.bbs", "");
		cookie.setMaxAge(Integer.parseInt(cktime));
		cookie.setValue(value);
		ActionContext.getContext().getResponse().addCookie(cookie);
		UserInfo auser=new UserInfo(u);
		if (checkLoginScore(auser)) {
			BBSScore.addScore(u.getUsername(), Score.get("login"), new Date()
					+ ":用户登录加分!");
		}
		return user;
	}

	public ActiveUser useCookie() {
		ActionContext.getContext().getSession().removeAttribute("bbsuser");
		Cookie[] cookies = ActionContext.getContext().getRequest().getCookies();
		if (cookies != null && cookies.length > 0) {
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equals("com.knife.bbs")) {
					String value = cookies[i].getValue();
					if (value.indexOf('_') > 0) {
						String userName = value
								.substring(0, value.indexOf("_"));
						String password = value
								.substring(value.indexOf("_") + 1);
						ActiveUser user = loginWithCK(userName, password,
								ActionContext.getContext().getRequest()
										.getRemoteAddr());
						ActionContext.getContext().getSession()
								.setAttribute("bbsuser", user);
						return user;
					}
				}
			}
		}
		//游客身份
		return guestIn();
	}

	private ActiveUser loginWithCK(String userName, String password, String ip) {
		ActiveUser user = null;
		com.knife.bbs.domain.UserInfo u = (com.knife.bbs.domain.UserInfo) this.dao.getBy(com.knife.bbs.domain.UserInfo.class, "userName",
				userName);
		if (u != null && password.equals(u.getPassword().trim())) {
			user = new ActiveUser();
			user.setUsername(userName);
			user.setIp(ip);
			user.setCurposition("当前位置");
			user.setPassword(u.getPassword().trim());
			user.setLogintime(new Date());
			u.setLastloginip(ip);
			u.setLogintimes(new Integer(u.getLogintimes() == null ? 1 : u
					.getLogintimes().intValue() + 1));
			this.dao.update(u);
			//ActiveUserService.join(user);
		}
		return user;
	}

	//游客身份
	public ActiveUser guestIn() {
		ActiveUser user = new ActiveUser();
		user.setIp(ActionContext.getContext().getRequest().getRemoteAddr());
		user.setUsername(ActionContext.getContext().getRequest()
				.getRemoteAddr());
		user.setLogintime(new Date());
		user.setPassword(" ");
		//this.dao.save(user);
		ActionContext.getContext().getSession().setAttribute("bbsuser", user);
		return user;
	}

	public Friend getUserFriend(String cid) {
		return (Friend) this.dao.get(Friend.class, cid);
	}

	public List queryUserFriend(String scope) {
		return this.dao.query(Friend.class, "1=1" + scope);
	}

	public IPageList queryUserFriends(String scope, int pageSize, int pageNo) {
		DbPageList pList = new DbPageList(Friend.class, scope, null);
		pList.doList(pageNo, pageSize);
		return pList;
	}

	public Number getUserMessageNum(UserInfo user) {
		Number num = 0;
		try{
			num = (Number) this.dao
				.uniqueResult("select count(*) from BBSDoc where status>=0  and  (parentId is null or (parentId='')) and inputUser='"
						+ user.getUsername() + "'");
		}catch(Exception e){}
		return num;
	}

	public Number getUserEliteMessageNum(UserInfo user) {
		Number num = (Number) this.dao
				.uniqueResult("select count(*) from BBSDoc where status>=0  and eliteMessage>0 and  (parentId is null or (parentId='')) and inputUser='"
						+ user.getUsername() + "'");
		return num;
	}

	public Number getUserReplyNum(UserInfo user) {
		Number num = (Number) this.dao
				.uniqueResult("select count(*) from BBSDoc where status>=0  and ( not (parentId is null or (parentId=''))) and inputUser='"
						+ user.getUsername() + "'");
		return num;
	}

	public UserInfo getUserInfo(String cid) {
		com.knife.bbs.domain.UserInfo auser=(com.knife.bbs.domain.UserInfo) this.dao.get(com.knife.bbs.domain.UserInfo.class, cid);
		if(auser!=null){
			return new UserInfo(auser);
		}else{
			return null;
		}
	}

	public UserInfo getUserInfoByName(String userName) {
		com.knife.bbs.domain.UserInfo auser=(com.knife.bbs.domain.UserInfo) this.dao.getBy(com.knife.bbs.domain.UserInfo.class, "userName", userName);
		if(auser!=null){
			return new UserInfo(auser);
		}else{
			return null;
		}
	}

	public List getLastRegUser(int topNum) {
		String scope = "status>=0 order by inputTime desc";
		DbPageList pList = new DbPageList(com.knife.bbs.domain.UserInfo.class, scope, null);
		pList.doList(1, topNum);
		return pList.getResult();
	}

	public IPageList queryUser(String scope, int pageSize, int pageNo) {
		DbPageList pList = new DbPageList(com.knife.bbs.domain.UserInfo.class, scope, null);
		pList.doList(pageNo, pageSize);
		return pList;
	}

	public boolean checkLoginScore(UserInfo user) {
		boolean ret = false;
		if (user != null) {
			Collection paras = new ArrayList();
			paras.add(user.getUsername());
			EasyJDB db = EasyJDB.getInstance();
			java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(
					"yyyy-MM-dd");
			Number num = (Number) db
					.uniqueResult("select count(*) from BBSScore where status>=0 and userName='"
							+ user.getUsername()
							+ "' and types='login' and vdate>='"
							+ dateFormat.format(new Date()) + "'");
			if (num.intValue() < 5)
				ret = true; // 通过登录每天最多可以加5分
		}
		return ret;
	}
}
